<template>
  <view class="wrap">
    <!-- <canvas canvas-id="qrcode" class="listl_cz" style="width: 100rpx;margin: 0 auto;" /> -->
    <swiper class="swiper" :autoplay="autoplay" :interval="interval" :duration="duration" previous-margin='80rpx' next-margin='50rpx' current="1" @change="changeSwiper">
      <swiper-item v-for="(item,index) in inviteImgs">
        <view class="swiper-item uni-bg-red">
          <view class="listl poster-container">
            <image class="listl_img" mode="widthFix" :src="item.pic"></image>
            <view class="listl_cy1">{{userInfo.nicknum}}</view>
            <!-- <image class="listl_cz" mode="widthFix" src="/static/mine/img24.png"></image> -->
            <!-- <uqrcode ref="uqrcode" canvas-id="qrcode" :value="url" :options="{ margin: 10 }" :size="100"></uqrcode> -->
            <!-- <canvas class="code" canvas-id="myQrcode" style="width: 400rpx;height:400rpx;margin: 200rpx 0;" @longtap="saveImg()"/> -->
            <canvas v-if="!qrCodeImg&&index===0" canvas-id="qrcode"
              style="width: 100%;height: 100%;opacity: 0;"></canvas>
            <!-- <canvas v-if="!qrCodeImg&&index===1" canvas-id="qrcode2" style="width: 100%;height: 100%;opacity: 0;"></canvas>
            <canvas v-if="!qrCodeImg&&index===2" canvas-id="qrcode3" style="width: 100%;height: 100%;opacity: 0;"></canvas> -->
            <image class="tupian" :src="qrCodeImg" mode="scaleToFill" />
            <!-- <canvas v-if="index===0" canvas-id="qrcode" class="listl_cz" style="width: 200rpx;margin: 0 auto;" /> -->
          </view>
        </view>
      </swiper-item>
    </swiper>
    <!-- <image class="img" mode="widthFix" src="/static/mine/img23.png"></image> -->
    <view class="dibude flex flex">
      <!-- <view class="dibudelic flex">
        <view class="dibudelic1">
          <image class="dibudelic1_img" mode="widthFix" src="/static/mine/img25.png"></image>
        </view>
        <view class="dibudelic2">微信</view>
      </view> -->
      <button class="dibudelic flex" open-type="share">
        <view class="dibudelic1">
          <image class="dibudelic1_img" mode="widthFix" src="/static/mine/img25.png"></image>
        </view>
        <view class="dibudelic2">微信</view>
      </button>
      <button class="dibudelic flex" @click="shareToTimeline">
        <view class="dibudelic1">
          <image class="dibudelic1_img" mode="widthFix" src="/static/mine/img26.png"></image>
        </view>
        <view class="dibudelic3">朋友圈</view>
      </button>
      <button class="dibudelic flex" @click="handleClick">
        <view class="dibudelic1">
          <image class="dibudelic1_img" mode="widthFix" src="/static/mine/img27.png"></image>
        </view>
        <view class="dibudelic3">下载</view>
      </button>
    </view>
    <!-- // 海报容器 -->
    <canvas canvas-id="canvass" id="canvas" style="width:290px; height: 463px;" />
    <!-- // 生成的海报图片 -->
    <image :src="imgAddRess" style=""></image>
  </view>
</template>

<script>
  import html2canvas from '@/common/html2canvas'
  import QRCode from '@/common/uqrcode'
  import uqrcode from '@/uni_modules/Sansnn-uQRCode/components/uqrcode/uqrcode'
  import {
    otherMa //邀请码背景
  } from '@/request/api.js'
  export default {
    components: {
      uqrcode
    },
    data() {
      return {
        openid: uni.getStorageSync('openid'), //获取缓存的openid
        userInfo: uni.getStorageSync('userInfo'), //授权后的信息
        background: ['#f00', '#f0f', '#ff0'],
        indicatorDots: true,
        autoplay: false,
        interval: 2000,
        duration: 500,
        inviteImgs: [], // 邀请码图片
        url: 'https://moshangweilai.herobing.com/login/welcome?pid=' + uni.getStorageSync('userInfo').id,
        qrCodeImg: uni.getStorageSync('qrCodeImg') || '',
        imgAddRess: "",
        shareBg: "",
        shareNicknum: '',
        shareQrImageUrl: "https://img2.baidu.com/it/u=3334525604,928778682&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1703955600&t=c88ebba9f3d8aeee92c6afd219945f9a",
        qrCodeImgChang:''
      };
    },
    onLoad(options) {
      console.log('进入邀请页--获取options')
      console.log(options)
      if (options.pid) {
        // 通过分享页面进的
        console.log('通过朋友圈分享来的')
        uni.setStorageSync('pid', options.pid)
      }
      this.otherMaFun()
      if (this.qrCodeImg === '') {
        this.uQrcodeFun('qrcode', this.url)
      }
      // this.createQrcode()
    },
    methods: {
      // 监听滑动
      changeSwiper(e){
        console.log('监听滑动')
        console.log(e)
        this.current = e.detail.current
        this.shareBg = this.inviteImgs[this.current].pic
      },
      // 获取邀请码背景--通过接口
      otherMaFun() {
        otherMa({
          openid: this.openid
        }).then(res => {
          console.log('邀请码背景')
          console.log(res)
          this.inviteImgs = res.data
          this.shareBg = res.data[1].pic
        })
      },
      // 生成二维码
      uQrcodeFun(id, text) {
        QRCode.make({
          canvasId: id, // 切记canvasId 里边的内容需要跟canvas里边canvas-id="qrcode"的名字一样
          componentInstance: this,
          text: text, // 转成二维码的内容
          size: 150, // 绘制大小，可根据自身需求可动态获取容器大小进行生成
          margin: 0,
          backgroundColor: '#ffffff', // 二维码背景颜色
          foregroundColor: '#000000', // 二维码颜色
          fileType: 'jpg', // 二维码图片格式
          errorCorrectLevel: QRCode.errorCorrectLevel.H,
          success: res => {
            uni.setStorageSync('qrCodeImg', res)
            this.qrCodeImg = res // 此图片为base64格式
          }
        })
      },


      shareToTimeline() {
        console.log('分享朋友圈')
        // uni.share({
        //   provider: 'weixin',
        //   type: 0,
        //   imageUrl: '', // 分享图片的URL，可以是网络图片
        //   title: '没有焦虑的未来', // 分享的标题
        //   success: function(res) {
        //     console.log('分享成功');
        //   },
        //   fail: function(err) {
        //     console.error('分享失败', err);
        //   }
        // });
        uni.share({
          provider: 'weixin', // 分享类型，微信的分享
          type: 5, // 分享内容类型，图文
          title: '没有焦虑的未来', // 分享的标题
          // description: '分享描述', // 分享的描述
          imageUrl: '', // 分享的图片链接
          href: this.url, // 分享的链接
          success: function() {
            console.log('分享成功');
          },
          fail: function(err) {
            console.error('分享失败', err);
          }
        });
      },

      // 下载
      handleClick() {
        const _this = this;
        uni.showLoading({
          title: '下载中...',
          mask: true, // 是否显示透明蒙层，防止触摸穿透
        });
        console.log('生成图片')
        console.log(this.qrCodeImg)
        // 将base64图片转成临时路径
        const base64 = this.qrCodeImg // base64码
        const time = new Date().getTime();
        const imgPath = wx.env.USER_DATA_PATH + "/poster" + time + "share" + ".png";
        //如果图片字符串不含要清空的前缀,可以不执行下行代码.
        const imageData = base64.replace(/^data:image\/\w+;base64,/, "");
        const fs = wx.getFileSystemManager();
        fs.writeFileSync(imgPath, imageData, "base64");
        fs.close()
        // _this.imgUrls.push(imgPath)
        _this.qrCodeImgChang = imgPath
        console.log(_this.qrCodeImgChang)
        // 将base64图片转成临时路径----end
        // 多张图片处理
        const Images = [this.shareBg, this.qrCodeImgChang];
        Promise.all(Images.map(img => uni.getImageInfo({
          src: img
        }))).then(
          imageInfos => {
            console.log('Images then>>>>>>', imageInfos);
            this.shareBg = imageInfos[0].path;
            this.shareQrImageUrl = imageInfos[1].path;

            //根据参数开始绘图
            this.createdCanvas().then((res1) => {
              console.log('kkkkkkkkkkkkkkkkkkkkkkkkkkkk')
              console.log(res1)
              // 绘制需要延迟，不然第一次加载为空白
              setTimeout(() => {
                // 将生成的canvas图片，转为真实图片-地址
                uni.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  canvasId: "canvass",
                  success: res => {
                    _this.imgAddRess = res.tempFilePath;
                    console.log('真实图片>>>>>>', res);
                    // 通过后端把图片传上去
                    uni.uploadFile({
                      url: 'https://moshangweilai.herobing.com/other/savepic', //上传接口地址
                      name: 'pic', //后端接收的文件参数名
                      filePath: res.tempFilePath, //要上传的文件路径
                      formData: {},
                      header: {
                        "Content-Type": "multipart/form-data"
                      },
                      success: (uploadFileRes) => {
                        console.log('后端返回的图片')
                        let resPic = JSON.parse(uploadFileRes.data).data.pic
                        console.log(resPic);
                        _this.imgAddRess = resPic
                        // 下载到手机相册
                        uni.downloadFile({
                          url: resPic, //图片地址
                          success: function(res) {
                            console.log('成功---下载图片', res);
                            //wx.saveImageToPhotosAlbum方法：保存图片到系统相册
                            uni.saveImageToPhotosAlbum({
                              filePath: res.tempFilePath, //图片文件路径
                              success: function(data) {
                                uni.hideLoading(); //隐藏 loading 提示框
                                // uni.showModal({
                                //   title: '提示',
                                //   content: '保存成功',
                                //   modalType: false,
                                // })
                                uni.showToast({
                                  icon: 'none',
                                  title: '下载成功'
                                })
                              },
                              // 接口调用失败的回调函数
                              fail: function(err) {
                                if (err.errMsg ===
                                  "saveImageToPhotosAlbum:fail:auth denied" || err
                                  .errMsg ===
                                  "saveImageToPhotosAlbum:fail auth deny" || err
                                  .errMsg ===
                                  "saveImageToPhotosAlbum:fail authorize no response"
                                  ) {
                                  wx.showModal({
                                    title: '提示',
                                    content: '需要您授权保存相册',
                                    modalType: false,
                                    success: modalSuccess => {
                                      wx.openSetting({
                                        success(settingdata) {
                                          console.log("settingdata",
                                            settingdata)
                                          if (settingdata
                                            .authSetting[
                                              'scope.writePhotosAlbum'
                                            ]) {
                                            wx.showModal({
                                              title: '提示',
                                              content: '获取权限成功,再次点击图片即可保存',
                                              modalType: false,
                                            })
                                          } else {
                                            wx.showModal({
                                              title: '提示',
                                              content: '获取权限失败，将无法保存到相册哦~',
                                              modalType: false,
                                            })
                                          }
                                        },
                                        fail(failData) {
                                          console.log("failData", failData)
                                        },
                                        complete(finishData) {
                                          console.log("finishData",
                                            finishData)
                                        }
                                      })
                                    }
                                  })
                                }
                              },
                              complete(res) {
                                uni.hideLoading(); //隐藏 loading 提示框
                              }
                            })
                          },
                          fail: function(err) {
                            console.log('失败---下载图片')
                            console.log(err)
                          }
                        })
                      },
                    })



                    // uni.downloadFile({
                    //   url: _this.imgAddRess,
                    //   success: (res => {
                    //     console.log('下载到手机相册')
                    //     console.log(res)
                    //     uni.saveImageToPhotosAlbum({
                    //       filePath: res.tempFilePath,
                    //       success: (res) => {
                    //         uni.showToast({
                    //           title: '保存成功',
                    //           icon: 'success',
                    //           duration: 1000
                    //         })
                    //       }
                    //     })
                    //   })

                    // })
                  },
                  fail: (err) => {
                    console.log('error', err)
                  }
                }, this);
              }, 1000);
            })
          }
        );



      },
      createdCanvas() {
        const _this = this;
        return new Promise((resolve, reject) => {
          //绘图上下文
          const ctx = uni.createCanvasContext('canvass', this);
          uni.createSelectorQuery()
            .in(this)
            .select('#canvas')
            .boundingClientRect(rect => {
              console.log('rect')
              console.log(rect)
              if (!rect) return
              // var width = rect.width;
              // var height = rect.height;
              var width = 290;
              var height = 463;
              // 背景图
              ctx.drawImage(_this.shareBg, 0, 0, width, height);
              // ID号
              ctx.setFillStyle('#101010');
              ctx.setTextAlign('left');
              ctx.font = "16px 'AvantGardeFont'"
              // ctx.fillText(this.userInfo.nicknum, Math.ceil(width * 0.32) + 150, Math.ceil(height * 0.103 * 2)-10);
              ctx.fillText(this.userInfo.nicknum, 209, 42);
              // 二维码区背景背景
              ctx.beginPath();
              // r:8 ,
              // 起始点
              ctx.moveTo(12, height - 92 + 8);
              // 左上角
              ctx.arcTo(12, height - 92, 12 + 8, height - 92, 8);
              // 右上角
              ctx.arcTo(width - 12, height - 92, width - 12, height - 92 + 8, 8);
              // 右下角
              ctx.arcTo(width - 12, height - 12, width - 12 - 8, height - 12, 8);
              // 左下角
              ctx.arcTo(12, height - 12, 12, height - 12 - 8, 8);
              ctx.fillStyle = 'transparent';
              ctx.closePath();
              ctx.fill();
              // ctx.clip(); // 裁剪
              ctx.restore(); // 恢复之前保存的绘图上下文
              // 二维码图片
              console.log('绘制二维码图片')
              console.log(_this.qrCodeImg)
              // uni.getImageInfo({
              // 			src: _this.qrCodeImg,
              // 			success: function (image) {
              // 				console.log('image-------------------');
              // 				console.log(image);
              // 			},
              //       fail: (err) => {
              //         console.log('error', err)
              //       }
              // 		});
              // var fs = uni.getFileSystemManager()
              // var save_path = uni.env.USER_DATA_PATH + '/' + (new Date()).getTime() + '.png';
              // fs.writeFile({
              //   filePath: _this.qrCodeImg,
              //   data: 'base64',
              //   encoding: 'base64',
              //   success: (res) => {
              //     //再使用save_path
              //     console.log('有效吗')
              //     console.log(res)
              //   },fail: (err) => {
              //       console.log('error', err)
              //     }
              // });
              ctx.drawImage(_this.qrCodeImgChang, width - 96, height - 150, 60, 60);
              ctx.draw();
            }).exec()
          //获取节点
          resolve()
        })
      },
    },

    // 分享微信好友
    onShareAppMessage(event) {
      console.log(event);
      return {
        title: '陌上未来，没有概率做了就赚',
        path: '/pages/index/index?pid=' + uni.getStorageSync('userInfo').id,
        // imageUrl: imageUrl
      }
    },
    //分享到朋友圈
    onShareTimeline(event) {
      console.log(event);
      return {
        title: '陌上未来，没有概率做了就赚',
        path: '/pages/index/index?pid=' + uni.getStorageSync('userInfo').id,
        query: 'pid=' + uni.getStorageSync('userInfo').id,
        // imageUrl: imageUrl
      }
    },


  }
</script>

<style scoped lang="scss">
  #canvas {
    margin-top: 200rpx;
  }

  button {
    padding: 0;
    margin: 0;
    background: none !important;
    border: none !important;
  }

  button::after {
    border: none;
  }

  .wrap {
    width: 100%;
    height: 100vh;
    background: #eee;
    overflow: hidden;
  }

  .swiper {
    width: 100%;
    height: 920rpx;
    padding: 30rpx 0rpx;
  }

  swiper {
    width: 580rpx;
    // height: 920rpx;
    height: 920rpx;
    padding: 0;
    margin: 0;
  }

  .listl {
    width: 580rpx;
    height: 920rpx;
    position: relative;

    .listl_img {
      width: 100%;
      height: 920rpx;
      position: absolute;
      top: 0;
      left: 0;

    }

    .listl_cy1 {
      font-family: 'AvantGardeFont';
      color: rgba(16, 16, 16, 1);
      font-size: 32rpx;
      position: absolute;
      right: 55rpx;
      top: 53rpx;
      width: 108rpx;
      text-align: center;
    }

    .listl_cz {

      // height: 160rpx;
      // width: 160rpx;
      // position: absolute;
      // right: 53rpx;
      // bottom: 168rpx;
      .listl_cz {
        height: 160rpx;
        width: 160rpx;
        position: absolute;
        right: 53rpx;
        bottom: 168rpx;
      }
    }

    .listl_c {
      width: 490rpx;
      height: 100rpx;
      position: absolute;
      z-index: 1;
      bottom: 50rpx;
      margin-left: 40rpx;


      .listl_cy2 {
        color: rgba(16, 16, 16, 1);
        font-size: 28rpx;
      }
    }

    .listl_cy {
      text-align: center;
      width: 200rpx;
    }
  }

  .dibude {
    width: 650rpx;
    height: auto;
    margin: 0 auto;
    margin-top: 70rpx;

    .dibudelic {
      width: 33.3%;
      text-align: center;
      flex-direction: column;

      .dibudelic1 {
        width: 132rpx;
        height: 132rpx;
        border-radius: 20rpx;
        text-align: center;
        line-height: 132rpx;
        background-color: rgba(255, 255, 255, 1);
        margin-bottom: 14rpx;

        .dibudelic1_img {
          width: 68rpx;
          height: auto;
          text-align: center;
          margin-top: 30rpx;

        }
      }

      .dibudelic2 {
        color: rgba(16, 16, 16, 1);
        font-size: 28rpx;
      }

      .dibudelic3 {
        color: rgba(137, 137, 137, 1);
        font-size: 28rpx;
      }
    }
  }

  canvas {
    width: 200rpx;
    height: 200rpx;
  }

  .tupian {
    width: 100rpx;
    height: 100rpx;
    position: absolute;
    bottom: 170rpx;
    right: 82rpx;
  }
</style>